<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="维护计划" prop="inspectionPlanId">
          <el-select
            v-model="searchParam.inspectionPlanId"
            placeholder="请选择维护计划"
            clearable
          >
            <el-option
              v-for="item in inspectionPlanList"
              :key="`${item.id}`"
              :label="`${item.planName}`"
              :value="`${item.id}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="维护班组" prop="executeTeamld">
          <el-select
            v-model="searchParam.executeTeamId"
            placeholder="请选择维护计划"
            clearable
          >
            <el-option
              v-for="item in crewList"
              :key="`${item.id}`"
              :label="`${item.teamName}`"
              :value="`${item.id}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务编号">
          <el-input
            v-model="searchParam.taskNo"
            placeholder="请输入任务编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="维护状态">
          <el-select
            v-model="searchParam.taskStatus"
            placeholder="请选择维护状态"
            clearable
          >
            <el-option
              v-for="item in useDictionary('EamInspectTaskStatus')"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="维护时间">
          <el-date-picker
            v-model="searchParam.inspectionDateSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getcreateTime"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <!-- <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableStop()"
          >批量停用</el-button
        >
      </template> -->

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        @sort-change="onTableSortChanged"
        border
      >
        <el-table-column
          label="序号"
          type="index"
          min-width="60"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="任务编号"
          prop="taskNo"
          min-width="150"
          show-overflow-tooltip
          sortable
        />
        <!-- <el-table-column
          label="维护任务"
          prop="taskName"
          min-width="200"
          show-overflow-tooltip
          align="left"
          sortable
        /> -->
        <el-table-column
          label="状态"
          prop="taskStatus"
          min-width="100"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            <!-- {{
              dictionaryStore.filterDictName(
                "EamInspectTaskStatus",
                scope.row.taskStatus
              )
            }} -->
            <el-tag v-if="scope.row.taskStatus == 2" type="success">{{
              useDictionary("MaintainTaskStatus", scope.row.taskStatus ?? "")
            }}</el-tag>
            <el-tag v-else>{{
              useDictionary("MaintainTaskStatus", scope.row.taskStatus ?? "")
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="维护进度"
          prop="inspectTotalNumber"
          min-width="150"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            <span style="color: #4251c9">
              未维护({{
                scope.row.notInspectedNumber ? scope.row.notInspectedNumber : 0
              }})</span
            >
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="维护路线"
          prop="inspectionRouteName"
          min-width="150"
          show-overflow-tooltip
          align="center"
        /> -->
        <el-table-column
          label="计划维护日期"
          prop="planExecuteTime"
          min-width="180"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            <span>{{
              scope.row.planExecuteTime ? scope.row.planExecuteTime : ""
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="维护开始时间"
          prop="startExecuteTime"
          min-width="180"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            <span>{{
              scope.row.startExecuteTime ? scope.row.startExecuteTime : ""
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="维护结束时间"
          prop="endExecuteTime"
          min-width="180"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            <span>{{
              scope.row.endExecuteTime ? scope.row.endExecuteTime : ""
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="维护班组"
          prop="executeTeamName"
          min-width="150"
          show-overflow-tooltip
          align="center"
          sortable
        />
        <!-- <el-table-column
          label="维护人"
          prop="executePersonNam"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column> -->

        <el-table-column fixed="right" label="操作" width="140" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <mold-maintainTask-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import { filterOrder } from "@/utils/commonHooks";
defineOptions({
  name: "EAMMOLDMAINTAINTASK",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/eam/mouldMaintainTask/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  inspectionPlanId: "",
  executeTeamId: "",
  taskNo: "",
  taskStatus: "",
  inspectionStartDate: "",
  inspectionEndDate: "",
  inspectionDateSearch: [],
};

const deleteParam = {
  api: "/qms/qmsexceptionsubtype/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  console.log(prop, order);

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  await request({
    url: `eam/mouldMaintainTask/getView/${id}`,
    method: "get",
  })
    .then((data) => {
      console.log(data.data);
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开问题二级分类表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改问题二级分类";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增问题二级分类";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开问题二级分类表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "维护记录详情";
  getInfo(roleObj.id);
  // addDialog.visible = true;
  addDialog.readvisible = false;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getcreateTime(data: any) {
  if (data) {
    searchParam.value.inspectionStartDate = data[0];
    searchParam.value.inspectionEndDate = data[1];
  } else {
    searchParam.value.inspectionStartDate = "";
    searchParam.value.inspectionEndDate = "";
  }
}

// async function deleteItem(id: any) {
//   ElMessageBox.confirm("确认删除该数据项?", "警告", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消",
//     type: "warning",
//   }).then(async () => {
//     await request({
//       url: `/qms/qmsexceptionsubtype/deleteItem/${id}`,
//       method: "post",
//     }).then((res) => {
//       ElMessage.success("删除成功！");
//       search();
//     });
//   });
// }

// async function handleTableStop(id: any) {
//   if (id) {
//     ElMessageBox.confirm("确认停用该数据项?", "警告", {
//       confirmButtonText: "确定",
//       cancelButtonText: "取消",
//       type: "warning",
//     }).then(async () => {
//       await request({
//         url: `/qms/qmsexceptionsubtype/stopUsing`,
//         method: "post",
//         data: { ids: [id] },
//       }).then((res) => {
//         ElMessage.success("停用成功！");
//         search();
//       });
//     });
//   } else {
//     ElMessageBox.confirm("确认停用已选中的数据项?", "警告", {
//       confirmButtonText: "确定",
//       cancelButtonText: "取消",
//       type: "warning",
//     }).then(async () => {
//       await request({
//         url: `/qms/qmsexceptionsubtype/stopUsing`,
//         method: "post",
//         data: { ids: ids.value },
//       }).then((res) => {
//         ElMessage.success("停用成功！");
//         search();
//       });
//     });
//   }
// }

// 获取维护计划列表
const inspectionPlanList = ref([]);
const getInspectionPlanList = async () => {
  await request({
    url: "/eam/mouldMaintainPlan/getList",
    method: "post",
    data: {},
  }).then((res) => {
    inspectionPlanList.value = res.data;
    console.log("inspectionPlanList", inspectionPlanList.value);
  });
};
// 获取维护班组列表
const crewList = ref([]);
const getCrewList = async () => {
  await request({
    url: "eam/eamTeam/getAvailableList",
    method: "post",
    data: {},
  }).then((res) => {
    crewList.value = res.data;
  });
};

onMounted(() => {
  getCrewList();
  getInspectionPlanList();
  getTableList();
});
</script>
